package com.js.data.system.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.js.data.common.utils.RedisUtils;
import com.js.data.system.entity.SysDictItem;
import com.js.data.system.service.DictItemService;
import com.js.data.system.vo.DictVO;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据字典工具类
 */
public class DictUtil {


    private final static String DICT_KEY = "dict:";
    private static RedisUtils redisUtil = SpringUtil.getBean(RedisUtils.class);

    private static DictItemService dictItemService = SpringUtil.getBean(DictItemService.class);


    /**
     * 根据类型获取字典列表
     *
     * @param dictKey 字典类型
     * @return {@link List<DictVO>}
     */
    public static List<DictVO> getSysDictList(String dictKey) {
        List<DictVO> redisDictList = redisUtil.getHashList(DICT_KEY + dictKey, DictVO.class);
        if (CollectionUtil.isEmpty(redisDictList)) {
            List<DictVO> dictList = putSysDict(dictKey);
            dictList.sort(Comparator.comparing(DictVO::getSortBy));
            return dictList;
        }
        redisDictList.sort(Comparator.comparing(DictVO::getSortBy));
        return redisDictList;
    }

    public static String getKeyLableByValue(String dictKey,String value){
        List<DictVO> lstDict =  getSysDictList(dictKey);
        return lstDict.stream().filter(dictVO -> dictVO.getValue().equals(value)).map(DictVO::getName).collect(Collectors.joining());
    }
    /**
     * 根据类型存储到redis中
     *
     * @param dictKey 字典类型
     * @return List<RedisDict> 现有的所有的字典
     */
    public static List<DictVO> putSysDict(String dictKey) {
        List<SysDictItem> items = dictItemService.listByKeyType(dictKey);
        List<DictVO> dictList = new ArrayList<>();
        items.forEach(data -> {
            DictVO dictVO = new DictVO();
            dictVO.setDictKey(data.getKeyType());
            dictVO.setName(data.getLabel());
            dictVO.setValue(data.getValue());
            dictVO.setSortBy(data.getSortBy());
            dictList.add(dictVO);
        });
        redisUtil.putHashList(DICT_KEY + dictKey, DictUtil::apply, dictList);
        return dictList;
    }

    public static Object apply(Object t) {
        DictVO dict = (DictVO) t;
        return dict.getValue();
    }

    /**
     * 根据key删除(hash列表)字典
     *
     * @param dictKey dictKey
     */
    public static void delSysDictList(String dictKey) {
        redisUtil.deleteValue(DICT_KEY + dictKey);
    }
}
